package com.item.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.DateUtil;
import com.item.dao.model.Subject;
import com.item.dao.model.SubjectDetail;
import com.item.dao.model.SubjectDetailExample;
import com.item.exception.JSONRepUtils;
import com.item.service.SubjectDetailService;
import com.item.service.SubjectService;
import com.item.util.SubjectUtils;

@Controller
public class SubjectDetailController {
	@Autowired
	private SubjectDetailService subjectService;
	
	@RequestMapping("/listSubject")
	@ResponseBody
	public String list(Page param,SubjectDetail subject) throws Exception{
		SubjectDetailExample example = new SubjectDetailExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		SubjectDetailExample.Criteria criteria = example.createCriteria();
		
		//以下两个字段用来做筛选  分别是title和source的模糊匹配
		if(StringUtils.isNotBlank(subject.getSubName())){
			criteria.andSubNameEqualTo(subject.getSubName());
		}
		if(StringUtils.isNotBlank(subject.getName())){
			criteria.andNameLike("%"+subject.getName()+"%");
		}
		if(subject.getHasBooks() != null){
			criteria.andHasBooksEqualTo(subject.getHasBooks());
		}
		example.setOrderByClause("sub_id ASC,top DESC");
		List<SubjectDetail> list = subjectService.selectByExample(example);
		return JSONRepUtils.serialize(new Page(PaginationSupport.getContext().getTotalCount(), list), 0);
	}
	
	@RequestMapping("/showlistSubject")
	public String list() {
		return "subject/subjectList";
	}
	
	@RequestMapping("/toEditSubject")
	public String toEdit()throws Exception{
		return "/subject/subjectEdit";
	}
	
	@RequestMapping(value="/saveSubject",method=RequestMethod.POST)
	@ResponseBody
	public String save(SubjectDetail subject, HttpSession session)throws Exception{
		//WebPageFileController fileController = new WebPageFileController("bs", "news", "utf8");
//		System.out.println(subject.getName());
		try{
			if(StringUtils.isBlank(subject.getId())){
				subject.setSubNumber(Integer.parseInt(subject.getSubId()));
				subject.setSubName(SubjectUtils.getSubjectByType(Integer.parseInt(subject.getSubId())));
				//首先检查这个日期的是否有了
				SubjectDetailExample sdex = new SubjectDetailExample();
				sdex.createCriteria().andSubIdEqualTo(subject.getSubId());
				sdex.setOrderByClause("top DESC");
				PaginationSupport.setContext(1, 1, null);
				List<SubjectDetail> details = subjectService.selectByExample(sdex);
				if(details == null || details.size() == 0){
					subject.setTop(0);
				}else{
					subject.setTop(details.get(0).getTop()+1);
				}
				subject.setCreateTime(new Date());
				subject.setHasBooks(0);
				subjectService.insert(subject);
			}else{
				subjectService.updateByPrimaryKeySelective(subject);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdSubject")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		SubjectDetail n = subjectService.selectByPrimaryKey(id);
		return JSONRepUtils.serialize(n, 0);
	}
	
	@RequestMapping("/delSubject")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
//		WebPageFileController fileController = new WebPageFileController();
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			subjectService.deleteByPrimaryKey(ids[i]);
//			fileController.deleteFile(urls[i]);
		}
		return "{\"success\":true}";
	}
	
	@RequestMapping("/moveUpSubject")
	@ResponseBody
	public String moveUp(String id,HttpSession session) throws Exception {
		return processMove(id, 0);
	}
	
	@RequestMapping("/moveDownSubject")
	@ResponseBody
	public String moveDown(String id,HttpSession session) throws Exception {
		return processMove(id, 1);
	}
	
	/**
	 * 操作上移下移的动作
	 * @param uid
	 * @param type
	 * @return
	 */
	public String processMove(String uid,int type){
		
		SubjectDetail now = subjectService.selectByPrimaryKey(uid);
		if(now == null){
			return "{\"success\":false}";
		}
		SubjectDetailExample sdex = new SubjectDetailExample();
		if(type == 0){
			sdex.createCriteria().andSubIdEqualTo(now.getSubId()).andTopGreaterThan(now.getTop());
			sdex.setOrderByClause("top ASC");
		}else{
			sdex.createCriteria().andSubIdEqualTo(now.getSubId()).andTopLessThan(now.getTop());
			sdex.setOrderByClause("top DESC");
		}
		PaginationSupport.setContext(1, 1, null);
		List<SubjectDetail> nexts = subjectService.selectByExample(sdex);
		if(nexts == null || nexts.size() == 0){
			return "{\"success\":false}";
		}
		SubjectDetail next = nexts.get(0);
		Integer top = next.getTop();
		next.setTop(now.getTop());
		subjectService.updateByPrimaryKeySelective(next);
		now.setTop(top);
		subjectService.updateByPrimaryKeySelective(now);
		return "{\"success\":true}";
	}
}

